package org.totoro.memory.ref;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 软引用
 * 回收时间：gc后发现内存还是不足，这时候就回收软引用对象
 * <p>
 * vm:-Xmx20m -verbose:gc -XX:+PrintGCDetails
 *
 * @author daocr
 * @date 2020/3/6
 */
public class SoftReferenceTest {

    public static final int _2MB = 1024 * 1024 * 2;


    public static void main(String[] args) throws InterruptedException {

        // 引用信息放到队列中
        ReferenceQueue<byte[]> referenceQueue = new ReferenceQueue<>();

        // 引用链路  ：  list 强引用 -> SoftReference 软引用 -> byte 数组
        List<SoftReference<byte[]>> softReferences = new ArrayList<>();

        for (int i = 1; i <= 10; i++) {
            byte[] bytes = new byte[_2MB];
            SoftReference<byte[]> softReference = new SoftReference<>(bytes, referenceQueue);

            softReferences.add(softReference);
            System.out.println("第" + i + "申请 2mb 内存" + bytes);

            for (SoftReference<byte[]> item : softReferences) {
                System.out.print(item.get() + "\t");
            }
            System.out.println();

            Thread.sleep(1000);

        }


        for (SoftReference<byte[]> softReference : softReferences) {
            System.out.println(softReference.get());
        }


    }

}
